package com.hm.health.Activity.ecgflash;

import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView;

import com.goodix.utils.TimeUtil;
import com.goodix.widget.AlertDialogEx;
import com.hm.health.Activity.BaseActivity;
import com.hm.health.R;
import com.hm.health.Utils.FileUtil;
import com.hm.health.adapter.EcgFlashSummaryAdapter;
import com.hm.health.entity.EcgFlashRecordBean;
import com.hm.health.entity.dao.EcgPatchCsvInfo;
import com.hm.health.entity.dao.EcgPatchSectorInfo;
import com.hm.health.records.ecgpatch.EcgPatchRecordReader;

import org.litepal.crud.DataSupport;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class EcgFlashSummaryActivity extends BaseActivity {
    public static final String TAG = "EcgFlashSummaryActivity";
    private static final String DATE_FORMAT = "%04d-%02d-%02d";
    @BindView(R.id.rv_ecg_records)
    RecyclerView mRvEcgRecords;
    @BindView(R.id.pb_ecg_progress)
    ProgressBar mPbEcg;
    @BindView(R.id.ecg_date_textview)
    TextView mTvDate;
    private EcgFlashSummaryAdapter mRecordAdapter;
    private List<EcgFlashRecordBean> mRecordList = new ArrayList<>();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ecg_history_summary);
        ButterKnife.bind(this);
        setCenterTitle(getString(R.string.ecg_flash_history_records));
        getSupportActionBar().setHomeButtonEnabled(true);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        long initTime = System.currentTimeMillis();
        mTvDate.setText(String.format(DATE_FORMAT, Integer.parseInt(TimeUtil.formateEcgTime(initTime).substring(0, 4)),
                Integer.parseInt(TimeUtil.formateEcgTime(initTime).substring(4, 6)),
                Integer.parseInt(TimeUtil.formateEcgTime(initTime).substring(6, 8))));
        mRecordAdapter = new EcgFlashSummaryAdapter(mRecordList, mContext);
        mRecordAdapter.setLongClickListener(new EcgFlashSummaryAdapter.OnClickListener() {
            @Override
            public void longClick(EcgFlashSummaryAdapter.ViewHolder holder, int position) {
                Log.d(TAG, "Long click remove item " + position + " / " + mRecordList.size());

                AlertDialogEx.Builder builder = new AlertDialogEx.Builder(mContext);
                builder.setMessage(getString(R.string.make_sure_delete_curret_record));
                builder.setPositiveButton(getString(R.string.ok), new View.OnClickListener(){
                    @Override
                    public void onClick(View view) {
                        if (position >= mRecordList.size()) {
                            return;
                        }
                        EcgFlashRecordBean bean = mRecordList.get(position);
                        // delete db csv record and sector record and csv files
                        DataSupport.deleteAll(EcgPatchCsvInfo.class, "testId = ?", bean.getTestRecordId());
                        DataSupport.deleteAll(EcgPatchSectorInfo.class, "testId = ?", bean.getTestRecordId());
                        for (int idx = 0; idx < bean.getRecordNum(); idx++) {
                            EcgFlashRecordBean.CsvFile csvFile = bean.getRecord(idx);
                            FileUtil.deleteFile(csvFile.recordPath);
                            FileUtil.deleteFile(csvFile.rawDataPath);
                        }
                        mRecordList.remove(position);
                        mRecordAdapter.notifyDataSetChanged();
                    }
                });
                builder.setNegativeButton(getString(R.string.cancel), null);
                builder.show();
            }
        });
        mRvEcgRecords.setAdapter(mRecordAdapter);
        loadGeneralSummaryList(mTvDate.getText().toString());
    }

    @Override
    protected void onDestroy() {
        EcgPatchRecordReader reader = EcgPatchRecordReader.getInstance();
        if (reader.isRecordLoaded()) {
            reader.unloadRecordBeanList();
            mRecordList.clear();
            mRecordAdapter.notifyDataSetChanged();
        }
        super.onDestroy();
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.home:
                finish();
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    private void loadGeneralSummaryList(String date) {
        EcgPatchRecordReader reader = EcgPatchRecordReader.getInstance();
        runOnUiThread(() -> {
            mPbEcg.setVisibility(View.VISIBLE);
            mRecordList.clear();
            mRecordAdapter.notifyDataSetChanged();
        });
        new Thread(() -> {
            String[] dateItems = date.split("-");
            String pathDate = dateItems[0] + dateItems[1] + dateItems[2];
            reader.unloadRecordBeanList();
            //reader.loadRecordBeanList(pathDate);
            reader.loadRecordBeanFromDB(pathDate);
            mRecordList.addAll(reader.getRecordBeanList());
            runOnUiThread(() -> {
                mPbEcg.setVisibility(View.GONE);
                mRecordAdapter.notifyDataSetChanged();
            });
        }).start();
    }

    @OnClick(R.id.ecg_date_layout)
    public void onDatePickerClicked() {
        showDatePickDialog((datePicker, year, month, day) -> {
            mTvDate.setText(String.format(Locale.ENGLISH, DATE_FORMAT, year, (month + 1), day));
            loadGeneralSummaryList(mTvDate.getText().toString());
            Log.d(TAG, "data: " + String.format(Locale.ENGLISH, DATE_FORMAT, year, (month + 1), day));
        }, mTvDate.getText().toString());
    }

    private void showDatePickDialog(DatePickerDialog.OnDateSetListener listener, String curDate) {
        if(curDate == null) {
            return;
        }
        Calendar calendar = Calendar.getInstance();
        int year = 0,month = 0,day = 0;
        try {
            Log.d(TAG, "curDate: " + curDate);
            year =Integer.parseInt(curDate.substring(0,curDate.indexOf("-"))) ;
            month =Integer.parseInt(curDate.substring(curDate.indexOf("-")+1,curDate.lastIndexOf("-")))-1 ;
            day =Integer.parseInt(curDate.substring(curDate.lastIndexOf("-")+1,curDate.length())) ;
        } catch (Exception e) {
            e.printStackTrace();
            year = calendar.get(Calendar.YEAR);
            month = calendar.get(Calendar.MONTH) + 1;
            day=calendar.get(Calendar.DAY_OF_MONTH);
        }

        DatePickerDialog datePickerDialog = new DatePickerDialog(mContext, AlertDialog.THEME_DEVICE_DEFAULT_LIGHT, listener, year, month, day);
        datePickerDialog.getDatePicker().setCalendarViewShown(true);
        datePickerDialog.getDatePicker().setSpinnersShown(false);
        datePickerDialog.setCanceledOnTouchOutside(false);
        datePickerDialog.show();
    }
}
